import axios from 'axios';
import { setLocal } from '@/utils/utils';
import store from '@/store';
import blogal from '@/utils/globalUrl';
import { setAppId, getAppId } from '@/utils/local'; // getAppId()
import { config } from '@/config';

const memoFun = function(fn) {
  const cache = {};
  return function(...args) {
    const _args = JSON.stringify(args);
    return cache[_args] || (cache[_args] = fn.apply(fn, args));
  };
};

const getConfig = () => {
  return axios.get('configMobile.json').then(async(res) => {
    try {
      const { data } = res;
      const { dType, name } = data;

      config.title = name;
      if (process.env.NODE_ENV === 'development') {
        res.data.ApiUrl = blogal.globalUrl;

        // TODO: console
        res.data.showConsole = false;
      }
      store.dispatch('task/setUrl', data.ApiUrl);
      if (dType === 'zdd') {
        res.data.appId = data.zddAppId;
      }

      if (dType === 'dd') {
        res.data.appId = data.ddAppId;
      }
      if (!getAppId()) {
        setAppId(res.data.appId);
      }
      setLocal({
        dType: dType
      });

      return res;
    } catch (e) {
      Promise.reject(e);
    }
  });
};

export default memoFun(getConfig);
